var g_grid;
var g_mask;
var g_dialog;
var g_validate;
var g_moment;
var g_monitor;
var g_formel;

var index_delete_confirm_msg = "确认删除此记录么？";

var index_batch_delete_confirm_msg = "确认删除选中记录么？";

var index_select_one_at_least_msg = "请至少选择一条记录";

var index_slimScroll_event_map = new HashMap();

var index_user_info = new Object()

//判断IE9 返回布尔值
var index_is_IE9 = /^.*MSIE\x20{1}9(?=\.[0-9]+){1}(?=.*Trident\/[5-9].0).*$/.test(navigator.userAgent);

// 防止dialog重复点击
var index_dialog_is_lock = false;

var index_urlParamObj = index_query_param_get();

var index_document_keydown=function(e)
{ //这里给function一个事件参数命名为e，叫event也行，随意的，e就是IE窗口发生的事件。
    var key = e.which; //e.which是按键的值
    if (key == 13) {
        return false;
    }
}

$(document).ready(function (){

	// IE9时添加IE9hack.css
	if (index_is_IE9) 
	{
		// document.write('<link rel="stylesheet" href="'+index_web_app_name+'css/ie9hack.css">');
		$("#IE9hackCSS").attr('href','css/ie9hack.css');
	}

	// 页面布局初始化
	index_initLayout();

	// 窗口大小改变事件
	$(window).resize(function() {
		$(this).stopTime();
		$(this).oneTime(100 ,function (){
			index_initLayout();
		});
	});

	// 插件全局初始化
	require([index_web_app_name+'js/plugin/grid/grid.js',
			 index_web_app_name+'js/plugin/mask/mask.js',
			 index_web_app_name+'js/plugin/dialog/dialog.js',
			 index_web_app_name+'js/plugin/menu/menu.js',
			 index_web_app_name+'js/plugin/validate/validate.js',
			 index_web_app_name+'js/lib/fullcalendar/js/moment.min.js',
			 index_web_app_name+'js/plugin/monitor/monitor.js',
			 index_web_app_name+'js/plugin/formel/formel.js',
			 index_web_app_name+'js/lib/underscore.js'] ,function (grid ,mask ,dialog ,menu ,validate ,moment ,monitor ,formel ,underscore){

		g_grid = grid;
		g_mask = mask;
		g_dialog = dialog;
		g_validate = validate;
		g_moment = moment;
		g_monitor = monitor;
		g_formel = formel;

		// 初始化菜单
		var  username=sessionStorage.getItem("username")
		$("#dropdownMenu2").html(username+'<span class="caret"></span>')
		menu.render($("#menu") ,{
			//url : "data/xd-menu.json",
			// url : "data/menu.json",
			url : "api/user/func",
			paramObj:{username:username}
			//url : "sysconfig/menuconfig/queryUserMenuTree?random="+Math.random()
		});

		// 组合键弹出搜索框
		$(document).keydown(function (e){
			if(e.keyCode == 70 && e.ctrlKey)
			{
		       g_mask.show(function (el){
		       	  var buffer = [];
		       	  buffer.push('<div class="w-all h-all prel">');
		       	  buffer.push('<div style="top:30%;width: 100%;text-align: center" class="pabs" data-flag="search-div">');
		       	  buffer.push('<input type="text" class="index_search">');
		       	  buffer.push('</div>');
		       	  buffer.push('</div>');
		       	  el.append(buffer.join(""));
		       	  el.find("[class=index_search]").focus();
		       	  $("[data-flag=search-div]").on("click.indexserch" ,function (){
		       		 e.preventDefault();
		       		 return false;
		       	  });
		       });

		       $(document).on("click.indexserch" ,function (){
		    		$("[class=um_mask]").remove();
		    		$(document).off(".indexserch");
		    	});

		       e.preventDefault();
		       return false;
		    }
		});

		$("body").css("opacity" ,"1");
	});
});

function index_initLayout(flag)
{
	var window_height = $(window).height();
	var pg_header = $("[class=pg-header]:visible").height() + $("[class=pg-logo]:visible").height()
	$("#pg-container").height(window_height - pg_header);
	$("#pg-content").height($("#pg-container").height() - index_getPadderMargin($("#pg-content")));
	$("#content_div").height(
								$("#pg-content").height()
											- index_getHeightWithPadderMargin($("#menu_title")) 
											- index_getPadderMargin($("#content_div"))
							);
}

function index_getPadderMargin(el){
	if (el.size() == 0)
	{
		return 0;
	}
	else
	{
		return parseInt(el.css("padding-top")) + parseInt(el.css("padding-bottom"))
		     + parseInt(el.css("margin-top")) + parseInt(el.css("margin-bottom"));
	}
}

function index_getHeightWithPadderMargin(el){
	if (el.size() == 0 || el.is(":hidden"))
	{
		return 0;
	}
	else
	{
		return el.height() + parseInt(el.css("padding-top")) + parseInt(el.css("padding-bottom"))
				+ parseInt(el.css("margin-top")) + parseInt(el.css("margin-bottom"));
	}
}

function index_getPadderMarginHeight(el)
{
	if (el.size() == 0 || el.is(":hidden"))
	{
		return 0;
	}
	else
	{
		return parseInt(el.css("padding-top")) + parseInt(el.css("padding-bottom"))
						+ parseInt(el.css("margin-top")) + parseInt(el.css("margin-bottom"));
	}
}

function um_ajax_get(options)
{
	options.type = 'GET';
	var web_app = index_web_app + index_soc_prefix;
	options.server && (web_app = options.server);
	options.url=web_app + options.url
	options.paramObj = (options.paramObj?options.paramObj:{})
	options.paramObj={param:JsonTools.encode(options.paramObj),date:new Date().getTime()},
	um_ajax(options);
}

function um_ajax_post(options)
{
	options.type = 'POST';
	var web_app = index_web_app + index_soc_prefix;
	options.server && (web_app = options.server);
	options.url=web_app + options.url
	options.paramObj = (options.paramObj?options.paramObj:{})
	// currentPageNum pageSize  默认1 和 1000
	if(!options.paramObj.currentPageNum)
		options.paramObj.currentPageNum = 1
	if(!options.paramObj.pageSize)
		options.paramObj.pageSize = 1000

	options.paramObj={param:JsonTools.encode(options.paramObj),date:new Date().getTime()}
			
	um_ajax(options);
}

function xd_ajax_get(options)
{
	// var web_app = index_web_app + index_xd_prefix;
	// options.url=web_app + options.url
	options.type = 'GET';
	options.codeKey = "code"
	options.successKey = "1"
	options.msgKey = "message"
	options.objKey = "result"
	options.paramObj&&options.paramObj.currentPageNum?options.paramObj.pageNo=options.paramObj.currentPageNum:""
	var cachTime=new Date().getTime()
	options.url=options.url+"?cachTime="+cachTime
	um_ajax(options);
}

function xd_ajax_post(options)
{
	// var web_app = index_web_app + index_xd_prefix;
	// options.url=web_app + options.url
	options.type = 'POST';
	options.codeKey = "code"
	options.successKey = "1"
	options.msgKey = "message"
	options.objKey = "result"
	options.contentType="application/json"
	options.paramObj.currentPageNum?options.paramObj.pageNo=options.paramObj.currentPageNum:""
	options.paramObj=JSON.stringify(options.paramObj)
	var cachTime=new Date().getTime()
	options.url=options.url+"?cachTime="+cachTime
	um_ajax(options);
}

function um_ajax(options)
{
	var defaultOpt = {
		type : "GET",
		successCallBack : null,
		failCallBack : null,
		failTip : true,
		isAsync : true,
		isLoad : true,
		paramObj : null,
		maskObj : '#pg-container',
		//maskObj : 'body',
		server : null,
		codeKey : "resultCode",
		successKey : 0,
		msgKey : "resultMsg",
		objKey : "resultObj",
		contentType:"application/x-www-form-urlencoded"
	}

	var options = $.extend(defaultOpt, options);
	// 是否使用遮罩
	if (options.isLoad)
	{
		g_dialog.waitingAlert(options.maskObj);
	}

	if (!options.paramObj)
	{
		options.paramObj = new Object();
	}

	// currentPageNum pageSize  默认1 和 1000
	if (!options.paramObj.currentPageNum)
	{
		options.paramObj.currentPageNum = 1;
	}
	if (!options.paramObj.pageSize)
	{
		options.paramObj.pageSize = 1000;
	}
	
	var web_app = index_web_app;
	options.server && (web_app = options.server);
	$.ajax({
		async: options.isAsync,
		type: options.type,
		url:   options.url,
		contentType:options.contentType,
		dataType: "json",
		timeout : 120000, //超时时间设置，单位毫秒
		data:options.paramObj,
		xhrFields: {
			withCredentials: true
		},
		beforeSend: function(request) {
                        request.setRequestHeader("token", sessionStorage.token);
                    },
		// headers: {
	 //        login_token: localStorage.soc_token
	 //    },
		success :function(data)
		{
			if (data[options.codeKey] == options.successKey)
			{
				if (options.successCallBack)
				{
					//options.successCallBack(JsonTools.decode(filterXSS(JsonTools.encode(data.resultObj))));
					options.successCallBack(data[options.objKey]);
				}
			}
			else
			{
				if (data.resultCode == "502")
				{
					if (index_urlParamObj.userToken){
						um_ajax_post({
							url : "reLogin?token=" + /*$.base64.encode(*/index_urlParamObj.userToken/*)*/,
							paramObj : {},
							successCallBack : function (){
								
							}
						})
					}
					else{
						window.location.href = "/login.html";
					}
				}
				if (data.resultCode == "508")
				{
					window.location.href = "/index.html#/" + data.url;
				}
				if (data.resultCode == "600")
				{
					window.location.href = "/login.html?type=license";
				}
				if (options.failCallBack)
				{
					options.failCallBack();
				}
				var msg = (data[options.msgKey]?data[options.msgKey]:"操作失败");
				if (options.failTip)
				{
					g_dialog.operateAlert(options.maskObj,msg,"error");
				}
			}
			if (options.isLoad)
			{
				g_dialog.waitingAlertHide(options.maskObj);
			}
		},
		error :function(e){
			if (e.status == 200 && e.statusText == "OK")
			{
				options.successCallBack(e.responseText);
			}
			if (options.isLoad)
			{
				g_dialog.waitingAlertHide(options.maskObj);
			}
			g_dialog.waitingAlertHide(options.maskObj);
			if(e.statusText == "timeout")
			{
				g_dialog.operateAlert(options.maskObj,"响应超时!","error");
				g_dialog.waitingAlertHide(options.maskObj);
			}
			if(index_urlParamObj.userToken){
				window.location.reload()
			}
		}
	});
}

function um_ajax_file(form ,opt)
{
	var defaultOpt = {
		successCallBack : null,
		failCallBack : null,
		isLoad : true,
		paramObj : null,
		maskObj : '#pg-container',
		codeKey : "resultCode",
		msgKey : "resultMsg",
		objKey : "resultObj"
	}

	var opt = $.extend(defaultOpt, opt);

	if (opt.isLoad)
	{
		g_dialog.waitingAlert(opt.maskObj);
	}

	form.ajaxSubmit({
		url : index_web_app + index_soc_prefix + opt.url,
		type : "post",
		dataType : "json",
		data : {param:JsonTools.encode(opt.paramObj)},
		xhrFields: {
			withCredentials: true
		},
		success : function (data){
			if (data.resultCode == 0)
			{
				if (opt.successCallBack)
				{
					opt.successCallBack(data[opt.objKey]);
				}
			}
			else
			{
				if (opt.failCallBack)
				{
					opt.failCallBack();
				}
				g_dialog.operateAlert(opt.maskObj,data[opt.msgKey] ,"error");
			}
			if (opt.isLoad)
			{
				g_dialog.waitingAlertHide(opt.maskObj);
			}
		},
		error : function (){
			if (opt.isLoad)
			{
				g_dialog.waitingAlertHide(opt.maskObj);
			}
			
		}
	});
}

function um_ajax_html(opt)
{
	$.ajax({
			type: "GET",
			url: opt.url,
			success :function(data)
			{
				if (opt.selector)
					opt.successCallBack($(data).find(opt.selector))
				else
					opt.successCallBack($(data))
			}
		});
}

function index_query_param_get()
{ 
	var url = window.location.hash.substr(1);
	var tmp = url.indexOf("?");
	url = url.substr(tmp);
	var theRequest = new Object(); 
	var tmpVal;
	if (url.indexOf("?") != -1)
	{ 
		var str = url.substr(1); 
		strs = str.split("&"); 
		for(var i = 0; i < strs.length; i ++)
		{
			tmpVal = unescape(strs[i].split("=")[1]);
			if (tmpVal == "undefined" || !tmpVal)
			{
				tmpVal = "";
			}
			theRequest[strs[i].split("=")[0]]=filterXSS(tmpVal);
		}
	}
	if ($("[data-id=monitorId]").val() != "" && $("[data-id=monitorId]").val() != undefined)
	{
		theRequest.monitorId = $("[data-id=monitorId]").val();
	}

	if ($("[data-id=param-assetId]").val() != "" && $("[data-id=param-assetId]").val() != undefined)
	{
		theRequest.assetId = $("[data-id=param-assetId]").val();
	}

	if ($("[data-id=param-monitorTypeId]").val() != "" && $("[data-id=param-monitorTypeId]").val() != undefined)
	{
		theRequest.monitorTypeId = $("[data-id=param-monitorTypeId]").val();
	}
	return theRequest;
}

function index_init(el)
{
	index_initLayout();
}


if (index_urlParamObj.hideResize != 1)
{
	var onWindowResize = function(){
	    //事件队列
	    var queue = [],
	 
	    indexOf = Array.prototype.indexOf || function(){
	        var i = 0, length = this.length;
	        for( ; i < length; i++ ){
	            if(this[i] === arguments[0]){
	                return i;
	            }
	        }
	        return -1;
	    };
	 
	    var isResizing = {}, //标记可视区域尺寸状态， 用于消除 lte ie8 / chrome 中 window.onresize 事件多次执行的 bug
	    lazy = true, //懒执行标记
	 
	    listener = function(e){ //事件监听器
	        var h = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight,
	            w = window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || document.body.clientWidth;
	 
	        if( h === isResizing.h && w === isResizing.w){
	            return;
	 
	        }else{
	            e = e || window.event;
	         
	            var i = 0, len = queue.length;
	            for( ; i < len; i++){
	                queue[i].call(this, e);
	            }
	 
	            isResizing.h = h,
	            isResizing.w = w;
	        }
	    }
	 
	    return {
	        add: function(fn){
	            if(typeof fn === 'function'){
	                if(lazy){ //懒执行
	                    if(window.addEventListener){
	                        window.addEventListener('resize', listener, false);
	                    }else{
	                        window.attachEvent('onresize', listener);
	                    }
	 
	                    lazy = false;
	                }
	 
	                queue.push(fn);
	            }else{  }
	 
	            return this;
	        },
	        remove: function(fn){
	            if(typeof fn === 'undefined'){
	                queue = [];
	            }else if(typeof fn === 'function'){
	                var i = indexOf.call(queue, fn);
	 
	                if(i > -1){
	                    queue.splice(i, 1);
	                }
	            }
	            return this;
	        },
	        execute: function (){
	        	for (var i = 0; i < queue.length; i++) {
	        		queue[i]();
	        	}
	        }
	    };
	}.call(this);
}


function index_form_init(el)
{
	el.find("[data-type=select]").each(function (){
    	var sel2 = $(this).select2({
    		width : "100%"
    	});
    	$(this).parent().append('<div class="select2-container-err"><input class="form-control input-sm" style="opacity:0"/></div>');
    	$(this).change(function (){
    		if ($(this).val() != "")
    		{
    			g_validate.clear([$(this)]);
    		}
    	});
    });

    if (el.find("[data-type=date]").size() > 0)
    {
    	var data_position = "bottom";
    	require(['timepicker'] ,function (timepicker){
    		el.find("[data-type=date]").each(function (){
    			var self = this;
    			var excute_mouseout_timeout;
    			var el_remove = $('<div class="pabs" style="right:40px;top:7px;z-index:3002;display:none"><i class="icon-remove"></i></div>');
    			$(this).after(el_remove)
    			$(this).mouseover(function (){
    				// 控制不执行mouseout
    				clearTimeout(excute_mouseout_timeout);
    				el_remove.show();
    			}).mouseout(function (){
    				excute_mouseout_timeout = setTimeout(function (){
    					el_remove.hide();
    				} ,500);
    			});
    			el_remove.click(function (){
    				$(self).val("");
    				el_remove.hide();
    				clearTimeout(excute_mouseout_timeout);
    			});
    			$(self).addClass("no-write");
				$(self).attr("readonly" ,"readonly");
				$(self).blur(function(){
					if($(self).val() == "")
					{
						if ($(this).attr("format-type") == "ymd")
							$(self).val(g_moment().format('YYYY-MM-DD'));
						else
							$(self).val(g_moment().format('YYYY-MM-DD HH:mm:ss'));
					}
					else
					{
						return;
					}
				});
    			var tmp_data_position = $(this).attr("data-position");
    			var tmp_type = $(this).attr("format-type");
    			data_position = (tmp_data_position || data_position);
    			timepicker.time($(this) ,{
    				position : data_position,
    				type : tmp_type
    			});
    		});
    	});
    }

    if (el.find("[data-type=checkbox]").size() > 0){
    	el.find("[data-type=checkbox]").each(function (){
    		$(this).wrap('<div class="checkbox dib mr5"><label class="i-checks"></label></div>')
    				.after('<i></i>' + $(this).attr("txt"))
    	})
    }
}

// 查询条件关闭
function index_search_div_remove_click(cb ,cbParam){}

// 生成一个上传元素
function index_create_upload_el(el)
{
	var id = el.attr("id");
	var buffer= [];
		buffer.push('<input type="file" id="'+id+'" name="'+id+'" data-classinput="form-control inline v-middle input-s" data-classbutton="btn btn-default" data-icon="false"  id="t1" style="position: absolute; clip: rect(0px, 0px, 0px, 0px);" tabindex="-1">')		
		buffer.push('<div class="bootstrap-filestyle input-group">')            
		buffer.push('<input type="text" disabled="" class="form-control" data-id="up_name">')            
		buffer.push('<span class="group-span-filestyle input-group-btn" tabindex="0">')            
		buffer.push('<label class="btn btn-default " for="'+id+'">')            
		buffer.push('<span class="glyphicon glyphicon-folder-open"></span> 选择文件')            
		buffer.push('</label></span></div></div>');
	var new_el = $(buffer.join(""));
	el.after(new_el);
	el.remove();
	new_el.change(function (){
		new_el.find("[data-id=up_name]").val($(this).val());
	});
}


function index_render_div(el ,opt){}

function index_ed_monitor_get(urlParamObj ,selElArray ,cb)
{
	g_dialog.waitingAlert();
	var ed_monitor_url = "monitorView/queryEdMonitor";
    urlParamObj.instStatus = 1;
    urlParamObj.monitorTypeNameLanguage = 1;
    urlParamObj.edId = urlParamObj.assetId;
    um_ajax_get({
        url : ed_monitor_url,
        paramObj : urlParamObj,
        isLoad : false,
        successCallBack : function (data){
           index_instance_type_get(data.edmonitorstore[1].monitorId ,selElArray ,cb);
        }
    });
}

function index_instance_type_get(monitorId ,selElArray ,cb)
{
	var instance_type_url = "monitorView/queryInstanceType";
    um_ajax_get({
        url : instance_type_url,
        paramObj : {monitorId:monitorId},
        isLoad : false,
        successCallBack : function (data){
            var selBuff = [];
            for (var i = 0; i < data.length; i++) {
                selBuff.push({id:data[i].codevalue ,text:data[i].codename});
            }
            for (var i = 0; i < selElArray.length; i++) {
            	selElArray[i].select2({
                  data: selBuff,
                  width:"100%"
	            });

	            selElArray[i].change();
            }
            g_dialog.waitingAlertHide();
        }
    });
}

Array.prototype.insert = function (index, item) {
  this.splice(index, 0, item);
};

// $(document).keydown(index_document_keydown);

function Encrypt(str)
{
	var monyer = new Array();
	var i, s, str;
	var key = "socsoc"
	var t;
	var j;
	for (i = 0; i < str.length; i++)
	{
		j = i % 6;
		monyer += String.fromCharCode(str.charCodeAt(i)^key.charCodeAt(j));
	}
	return monyer;
}

function index_title_set(title)
{
	$("#menu_title_content").html('<a class="__back" href="javascript:history.go(-1);">返回</a> | ' + title)
}

function index_list_search_render(el ,opt){
	var placeholder = opt.placeholder || "请输入查询内容"
	el.append('<input placeholder="'+placeholder+'"></input>')
	el.append('<i class="icon-search"></i>')
	el.find("i").click(function (){
		opt.cbf(el.find("input").val())
	})
	el.find("input").bind("keypress" ,function (e){
		if (e.keyCode == "13")
			opt.cbf(el.find("input").val())
	})
}